package com.cyy.common.utils;

import com.cyy.common.pojo.dto.EmailDto;
import com.cyy.common.pojo.dto.EmailSendDto;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.util.Date;
import java.util.Optional;

@Slf4j
public class EmailUtils {


    /**
     * 发送邮件
     *
     * @param dto
     */
    public static void sendEmail(EmailSendDto dto) {
        try {
            //创建一个MINE消息
            MimeMessage mimeMessage = dto.getMailSender().createMimeMessage();
            MimeMessageHelper mineHelper = new MimeMessageHelper(mimeMessage, true);
            // 设置邮件主题
            mineHelper.setSubject(dto.getSubject());
            // 设置邮件发送者
            mineHelper.setFrom(dto.getFrom());
            // 设置邮件接收者，可以有多个接收者，中间用逗号隔开
            mineHelper.setTo(dto.getTo());
            // 设置邮件发送日期
            mineHelper.setSentDate(new Date());
            // 设置邮件的正文
            mineHelper.setText(dto.getTemplate(), dto.getIsHtml());
            // 发送邮件
            dto.getMailSender().send(mimeMessage);
        } catch (MessagingException e) {
            log.error("系统异常，无法正常发送验证码");
        }
    }


    /**
     * 生成 JavaMailSender
     *
     * @param dto
     * @return
     */
    public static JavaMailSenderImpl generateSender(EmailDto dto) {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(dto.getHost());
        mailSender.setPort(dto.getPort());
        mailSender.setUsername(dto.getUserName());
        mailSender.setPassword(dto.getPassword());
        mailSender.setDefaultEncoding(Optional.ofNullable(dto.getEncoding()).orElse("UTF-8"));
        return mailSender;
    }
}
